/*
 * 编辑完成后的操作 保存 另存为长图 同步到微信 数据前端验证
 */
define( [
  'jquery',
  'require',
  '../../lib/editData',
  'message',
  'combiner',
  'api',
  '../../lib/utils',
  'bigwe_utils',
  'constants',
  '../../modules/autoSave',
  'artCategory',
  '../../lib/dataHandle',
  '../../modules/createEditor'
], function( $, require ) {

  var c = require( 'constants' );
  var bu = require( 'bigwe_utils' );
  var dh = require( '../../lib/dataHandle' );
  var uts = require( '../../lib/utils' );
  var ue = require( '../../modules/createEditor' );
  var combiner = require( 'combiner' );
  var category = require( 'artCategory' ).CATEGORY_NAME;
  var AutoSave = require( '../../modules/autoSave' );
  var editData = require( '../../lib/editData' );
  var BIGWE_API = require( 'api' );
  var ShowTitleMessage = require( 'message' );

  var showTime = ShowTitleMessage.showTime;
  var self = $( '.save-sycn-send' );

  var beforeSubmit = {
    submitCheck: function( obj ) {
      //return this._isNullCheck(obj);
      for ( i in obj ) {
        var articleObj = obj[ i ];
        if ( articleObj.templateCheck ) {
          if ( !articleObj.content ) {
            ShowTitleMessage.showWarning( '请先输入一段正文，再生成模板。', showTime );
            return false;
          } else {
            continue;
          }
        }

        //  全局的标题长度验证
        if ( articleObj.title.length > 64 ) {
          ShowTitleMessage.showWarning( '标题长度不能超过64个字', showTime );
          $( '.article-title-input .title-input' ).trigger( 'focus' );
          this.graphEditTrigger( i );
          return false;
        }

        //  全局的作者长度验证（字符长度的验证）
        if ( bu.getStrChartLen( articleObj.author ) > 16 ) {

          ShowTitleMessage.showWarning( '作者长度不能超过8个字', showTime );
          $( '.article-author-input .author-input' ).trigger( 'focus' );
          this.graphEditTrigger( i );
          return false;

        }
        if ( articleObj.isAllCheck == 0 ) {
          if ( !articleObj.title && !articleObj.content ) {
            this.graphEditTrigger( i );
            ShowTitleMessage.showWarning( '请先输入标题或一段正文，再点击保存按钮。', showTime );
            return false;
          }
          /*var check = this._isNullTitleCheck( articleObj, i ) && this._contentCheck( articleObj, i );
          if ( !check ) {
            return false;
          }*/
        } else if ( articleObj.isAllCheck == 1 ) {
          // 全属性check
          var check = this._isNullTitleCheck( articleObj, i ) && this._contentCheck( articleObj, i ) && this._resourceUrlCheck( articleObj, i ) && this._categoryCheck( articleObj, i ) && this._tagsIsNullCheck( articleObj, i ) && this._resourceUrlCheck( articleObj, i );
          if ( !check ) {
            return false;
          }
        } else if ( articleObj.isAllCheck == 2 ) {
          // 标题、正文和封面check
          var check = this._isNullTitleCheck( articleObj, i ) && this._contentCheck( articleObj, i ) && this._imageCheck( articleObj, i );
          if ( !check ) {
            return false;
          }
        }
      }
      // 返回一段替换掉refer的内容
      return this._tencentImgReplace( obj );
    },
    graphEditTrigger: function( key ) {
      if ( !key || editData.editIndex === key * 1 ) return;
      $( '.js_writing', $( '.graph-manage>.comb-list>li' ).eq( key ) ).trigger( 'click' );
      //$('.graph-manage>.comb-list>nth-child(' + key + ') .js_writing').trigger('click');
    },
    // 空验证
    _isNullTitleCheck: function( obj, key ) {
      var article = obj;
      if ( !article.title ) {
        this.graphEditTrigger( key );
        ShowTitleMessage.showWarning( '您可以先把标题补充完整', showTime );
        return false;
      }
      return true;
    },
    // 文章内容验证
    _contentCheck: function( obj, key ) {
      if ( !obj.content ) {
        this.graphEditTrigger( key );
        ShowTitleMessage.showWarning( '您可以先写点正文', showTime );
        return false;
      }
      return true;
    },
    // 原文地址验证
    _resourceUrlCheck: function( obj, key ) {
      var resourceURL = $.trim( obj.source_url );
      if ( obj.isSource_url ) {
        if ( !resourceURL ) {
          ShowTitleMessage.showWarning( '原文链接已勾选，请输入链接地址', showTime );
          this.graphEditTrigger( key );
          $( 'input', '.unchangewidth-div .input-srcurl' ).addClass( 'checkError' );
          return false;
        } else {
          if ( !bu.isUrlCheck( resourceURL ) ) {
            ShowTitleMessage.showWarning( '请填写合法的原文地址', showTime );
            this.graphEditTrigger( key );
            $( 'input', '.unchangewidth-div .input-srcurl' ).addClass( 'checkError' );
            return false;
          }
        }
      }
      return true;
    },
    // 分类验证
    _categoryCheck: function( obj, key ) {
      var articleCategory = $.trim( obj.article_field );
      var _this = this;
      if ( !articleCategory ) {
        //ShowTitleMessage.showWarning('请先给该文章选择一个分类', showTime);
        this.graphEditTrigger( key );
        $( '#classify_pop .label_pop_nrmde' ).empty();

        function classify_pop( param ) {
          ShowTitleMessage.show( '正在为您推荐分类' );
          $.ajax( {
            type: 'post',
            dataType: 'json',
            url: '/recommend_tags/recommend_category',
            success: function( data ) {
              ShowTitleMessage.hide();
              if ( data.ret === 0 ) {
                var label_data = data.data;

                for ( var i in label_data ) {

                  $( '#classify_pop .label_pop_nrmde' ).append( '<span category_id="' + label_data[ i ].category_code + '">' + label_data[ i ].name + '</span>' )
                }
                $( '#classify_pop' ).modal( 'show' );
              }
            }
          } );
        };
        classify_pop();

        function categoryHtmlCreate( categoryKey ) {
          return '<li role="presentation">' +
            '<a role="menuitem" tabindex="-1" href="javascript: void(0);" category_id="' + categoryKey + '">' + category[ categoryKey ] + '</a>' + '</li>';
        }
        for ( key in category ) {
          $( '#classify_pop .dropdown-menu' ).append( categoryHtmlCreate( key ) );
        }
        $( '#classify_pop .dropdown-menu' ).on( 'click', 'a', function() {
          var _val = $( this ).text();
          $( this ).parent( 'li' ).addClass( 'selected' ).siblings().removeClass( 'selected' );
          $( '#classify_pop .dropdown #classify_xz' ).find( '.wenb' ).text( _val );
        } );
        $( '#classify_pop .dropdown-menu li:first-child a' ).trigger( 'click' );
        $( '#classify_pop .label_pop_nrmde' ).off( 'click', 'span' )
        $( '#classify_pop .label_pop_nrmde' ).on( 'click', 'span', function() {

          if ( !$( this ).hasClass( 'selected' ) ) {
            $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
          } else {
            $( this ).removeClass( 'selected' )
          }

        } );
        $( '#classify_pop .btn-confirm' ).off( 'click' );
        $( '#classify_pop .btn-confirm' ).click( function() {
          var _switch = $( '#classify_pop .label_pop_nrmde span' ).hasClass( 'selected' ),
            $categoryID = "",
            _val = "";

          if ( _switch ) {
            $categoryID = $( '#classify_pop .label_pop_nrmde span.selected' ).attr( 'category_id' );
            _val = $( '#classify_pop .label_pop_nrmde span.selected' ).text();
          } else {
            $categoryID = $( '#classify_pop .dropdown-menu li.selected a' ).attr( 'category_id' );
            _val = $( '#classify_pop .dropdown-menu li.selected a' ).text();
          }

          $( '#cate-text-div' ).text( _val );
          if ( $categoryID ) {
            // 数据编辑
            editData.setAttrbute( "article_field", $categoryID )
          }
          $( '#classify_pop' ).modal( 'hide' );
          // 触发保存并发送的事件

          editData.editType === '1' ?
            $( '#save-release', self ).trigger( 'click' ) :
            $( '#save-send', self ).trigger( 'click' );
          //_this._tagsIsNullCheck(obj, key);
        } );

        return false;
      }
      return true;
    },
    // 标签验证
    _tagsIsNullCheck: function( obj, key ) {
      if ( !$.trim( obj.article_label ) ) {
        //ShowTitleMessage.showWarning('请先给该文章至少添加一个标签', showTime);
        var $thisTag = $( '#label_pop' );
        this.graphEditTrigger( key );
        var $editColumn2 = $( '.edit-column>.edit-column2' );
        $( '.label_pop_nrmde', $thisTag ).empty();

        function label_pop() {
          ShowTitleMessage.show( '正在为您推荐标签' );
          $( '.js_nodata', $thisTag ).addClass( 'hide' );
          $.ajax( {
            type: 'post',
            dataType: 'json',
            url: '/recommend_tags/recommend_tags',
            data: {
              title: $( '.article-title-input>.edit-input', $editColumn2 ).val(),
              content: ue.getContentTxt()
            },
            success: function( data ) {
              ShowTitleMessage.hide();
              if ( data.ret === 0 ) {
                $( '#label_pop' ).modal( 'show' );
                var label_data = data.data;
                var html = '';

                ( label_data[ 'select' ] || [] ).forEach( function( item ) {
                  html += '<span class="selected">' + item + '</span>';
                } );
                ( label_data[ 'tags' ] || [] ).forEach( function( item ) {
                  html += '<span>' + item + '</span>';
                } );
                !html && $( '.js_nodata', $thisTag ).removeClass( 'hide' );
                $( '#label_pop .label_pop_nrmde' ).append( html );
              }
            }
          } );
        };
        label_pop();
        var tag_xz = 0;
        $( '.add_label' ).empty();
        $( '#label_pop .label_pop_nrmde' ).off( 'click', 'span' );
        $( '#label_pop .label_pop_nrmde' ).on( 'click', 'span', function() {
          tag_xz = $( '#label_pop span.selected' ).length;
          if ( !$( this ).hasClass( 'selected' ) && tag_xz < 5 ) {
            $( this ).addClass( 'selected' )
          } else {
            $( this ).removeClass( 'selected' )
          }
        } );
        $( '#label_pop .shurk input' ).bind( 'keypress', function( event ) {
          if ( event.keyCode == "13" ) {
            var _val = $( this ).val();
            tag_xz = $( '#label_pop span.selected' ).length;
            if ( bu.strlen( _val ) == 1 ) {
              $( this ).trigger( 'focus' );
              ShowTitleMessage.showWarning( "标签至少为一个汉字或两个字符哦", showTime );
            } else if ( bu.strlen( _val ) > 20 ) {
              ShowTitleMessage.showWarning( "标签最多为20字符哦", showTime );
            } else {
              if ( tag_xz < 5 ) {
                var flag = false;
                $( '#label_pop span' ).each( function() {
                  var span_text = $( this ).text();
                  if ( span_text === _val ) {
                    ShowTitleMessage.showWarning( "已存在相同的标签", showTime );
                    flag = false;
                    return false;
                  } else {
                    flag = true;
                  }
                } );
                if ( flag && _val != '' ) {
                  $( '.add_label' ).append( '<span class="selected">' + _val + '</span>' );
                  $( this ).val( '' );
                }

              } else {
                ShowTitleMessage.showWarning( "标签最多只能选择五个哦", showTime );
              }
            }
          }
        } );
        $( '#label_pop .shurk button' ).click( function() {
          var _val = $( this ).prev( 'input' ).val();
          tag_xz = $( '#label_pop span.selected' ).length;
          if ( bu.strlen( _val ) == 1 ) {
            $( this ).trigger( 'focus' );
            ShowTitleMessage.showWarning( "标签至少为一个汉字或两个字符哦", showTime );
          } else if ( bu.strlen( _val ) > 20 ) {
            ShowTitleMessage.showWarning( "标签最多为20字符哦", showTime );
          } else {
            if ( tag_xz < 5 ) {
              var flag = false;
              $( '#label_pop span' ).each( function() {
                var span_text = $( this ).text();
                if ( span_text === _val ) {
                  ShowTitleMessage.showWarning( "已存在相同的标签", showTime );
                  flag = false;
                  return false;
                } else {
                  flag = true;
                }
              } );
              if ( flag && _val != '' ) {
                $( '.add_label' ).append( '<span class="selected">' + _val + '</span>' );
                $( this ).prev( 'input' ).val( '' );
              }

            } else {
              ShowTitleMessage.showWarning( "标签最多只能选择五个哦", showTime );
            }
          }

        } );
        $( '.add_label' ).on( 'click', 'span', function() {
          $( this ).remove();
        } );
        var tageStr = '';
        $( '#label_pop .btn-confirm' ).off( 'click' );
        $( '#label_pop .btn-confirm' ).click( function( e ) {
          if ( $( '#label_pop span.selected' ).length == 0 ) {
            ShowTitleMessage.showWarning( "请选择标签", showTime );
            return false;
          }
          $( '#label_pop span.selected' ).each( function() {
            var thisText = $( this ).text() + ',';
            tageStr += thisText;

            $( '.tage-content .content', '.categoryAndTag-div' ).append( '<div title="' + $( this ).text() + '">' + $( this ).text() + '</div>' );
            $( '.tage-content .input-tage>.spa_gray' ).hide();


          } );
          if ( $( '.tage-content .content>div', '.categoryAndTag-div' ).length < 5 ) {
            uts.inputwidthset();
          } else {
            $( '.tage-content .input-tage .tag-input' ).hide();
          }
          tageStr = tageStr.substr( 0, tageStr.lastIndexOf( ',' ) );
          editData.setAttrbute( "article_label", tageStr );
          $( '#label_pop' ).modal( 'hide' );
          editData.editType === '1' ?
            $( '#save-release', self ).trigger( 'click' ) :
            $( '#save-send', self ).trigger( 'click' );
          e.stopPropagation();
        } );

        return false;
      }
      return true;
    },
    // 摘要抓取前54个字
    _abstractCheck: function( obj ) {
      for ( key in obj ) {
        var article = obj[ key ];
        var contentText = $( article.content ).text();
        if ( contentText ) {
          contentText = $.trim( contentText ).replace( /\n|\t/g, '' );
        }
        if ( !$.trim( article.desc ) ) {
          if ( contentText && contentText.length > 54 ) {
            article.desc = contentText.substr( 0, 54 );
          } else {
            article.desc = contentText;
          }
        }
      }
      return this._tencentImgReplace( obj );
    },
    // 封面的验证
    _imageCheck: function( obj, key ) {
      if ( !obj.cdn_url ) {
        ShowTitleMessage.showWarning( '请选择一个封面或输入一个图片地址', showTime );
        this.graphEditTrigger( key );
        return false;
      } else {
        return true;
      }
    },
    // 链接地址替换
    _tencentImgReplace: function( obj ) {
      for ( i in obj ) {
        for ( j in obj[ i ] ) {
          var val = obj[ i ][ j ];
          if ( typeof val == 'string' ) {

            obj[ i ][ j ] = val.replace( c.img02StoreRegxDomain, '' ).replace( c.img02StoreRegx, '' );

          }
        }
      }
      return JSON.stringify( obj );
    }
  };
  var returnParam = {
    // 异步操作的验证
    asyncBeforeSub: function( obj, fn ) {
      var $this = this;
      // 封面有效验证
      ! function _coverCheck() {
        // 需要验证的长度
        var objLength = 0;
        for ( i in obj ) {
          if ( obj[ i ].isAllCheck ) {
            objLength++;
          }
        }
        if ( !objLength ) {
          if ( fn ) {
            fn.call( $this, !0 );
            return 1;
          }
        }
        // 验证成功的长度
        var checkSuccessLen = 0;
        var isReturned = false;

        function triggerClick( i ) {
          beforeSubmit.graphEditTrigger( i );
          var obj = $( '.cover-input', '.edit-details' ).addClass( 'checkError' );
          setTimeout( function( argument ) {
            obj.trigger( 'focus' );
          }, .5e3 );
        }
        for ( var i in obj ) {

          if ( !obj[ i ].isAllCheck ) {
            continue;
          }

          if ( !$.trim( obj[ i ].cdn_url ) ) {
            ShowTitleMessage.showWarning( '请先上传或选择一个封面', showTime );
            triggerClick( i );
            fn.call( $this, 0 );
            return 0;
          }

          try {
            new URL( obj[ i ].cdn_url );
          } catch ( e ) {
            ShowTitleMessage.showWarning( '无效的封面地址！', showTime );
            triggerClick( i );
            fn.call( $this, 0 );
            return 0;
          }
          /*bu.prepImageRequest( obj[ i ].cdn_url, i, function( img, callbackParam ) {
            if ( img.src.indexOf( c.resPath + '/images/wuyulantu.png' ) === -1 ) {
              checkSuccessLen++;
            } else {
              if ( !isReturned ) {
                ShowTitleMessage.showWarning( '无效的封面地址！', showTime );
                triggerClick( callbackParam );
                isReturned = true;

                fn.call( $this, 0 );
                return 0;
              }
            }
            if ( objLength === checkSuccessLen ) {
              // 异步执行完成
              if ( fn ) {
                fn.call( $this, !0 );
              }
            }
          } );*/
        }

        fn && fn.call( $this, !0 );

      }();
    },
    // 提交数据保存(图文)
    graphSubmit: function( obj, fn ) {
      $this = this;
      $.ajax( {
        type: 'POST',
        url: BIGWE_API.EDIT_TEXT.SAVE_ORIGINAL_ARTICLE,
        data: {
          save_data: obj,
          article_group: editData.articleGroup
        },
        success: function( data ) {

          if ( typeof data != 'object' ) data = $.parseJSON( data );
          if ( data.ret !== 0 ) {
            fn && fn.apply( $this, arguments );
            return ShowTitleMessage.showWarning( data.msg, showTime );
          }
          data = $.parseJSON( data.oldApi );
          if ( !data.group ) {
            if ( data.error ) {
              ShowTitleMessage.showWarning( data.msg, showTime );
              if ( data.index ) {
                $( '.js_writing', $( '.graph-manage>.comb-list>li' ).eq( data.index - 1 ) ).trigger( 'click' );
              }
            } else {
              ShowTitleMessage.showWarning( data.status || '出现了未知的问题:-(，您可以尝试重新操作', showTime );
            }
            return;
          }
          var num = 0;
          if ( data.article_id ) {
            for ( var key in editData.graphDataDetails ) {
              editData.graphDataDetails[ key ].article_id = data.article_id[ num ];
              num++;
            }
          }
          ShowTitleMessage.show( data.status, showTime );
          editData.articleGroup = data.group;
          // 保存成功 清除自动保存的内容
          AutoSave.clear();
          if ( fn ) {
            fn.call( $this, data.group, editData.graphDataDetails[ 0 ].title );
          }
        },
        complete: function() {
          $( 'button', self ).removeAttr( 'disabled' );
        },
        error: function() {
          ShowTitleMessage.showWarning( '保存失败', showTime );
        }
      } );
    },
    // 提交数据保存(文章)
    articleSubmit: function( obj, fn ) {
      $this = this;
      if ( !obj.declare_original ) {
        delete obj.bigweFirst;
        delete obj.resourceUrl;
        delete obj.authorName;
        delete obj.platfName;
        delete obj.reprintSet;
      }
      // 将老对象转换成新对象去保存
      obj = dh.articleObjTransition( obj, false );
      $.ajax( {
        type: 'POST',
        url: BIGWE_API.EDIT_TEXT.SAVE_ART,
        //dataType: 'json',
        data: obj,
        success: function( data ) {
          data = typeof data === 'object' ? data : $.parseJSON( data );

          if ( !data.ret ) {
            if ( data.data.cd ) editData.setAttrbute( 'article_id', data.data.cd, !0 );
            ShowTitleMessage.show( '保存成功！', showTime );
            // 保存成功
            AutoSave.clear();
          } else {
            ShowTitleMessage.showWarning( data.msg, showTime );
          }
          if ( fn ) {
            fn( data );
          }
        },
        complete: function() {
          $( 'button', self ).removeAttr( 'disabled' );
        },
        error: function() {
          ShowTitleMessage.showWarning( '保存失败', showTime );
        }
      } );
    },
    // 进行保存操作
    doSaveGraph: function( fn, filedFn ) {

      var $this = this;
      var graphData = beforeSubmit.submitCheck( editData.graphDataDetails );

      function checkError() {

        return function() {
          editData.getCurrentArticle()[ 'need_publish' ] = '0';
          if ( $.isFunction( filedFn ) ) {
            filedFn();
          }
        }
      }
      if ( graphData ) {
        var result = returnParam.asyncBeforeSub( typeof graphData === 'object' ? graphData : $.parseJSON( graphData ), function( isSuccess ) {
          if ( isSuccess ) {
            // 所有验证通过
            $this.saveSuccess = fn;
            $this.graphData = graphData;
            // 进行原创验证
            //$this.reprintCheck($this.normalSave, checkError());
            $this.normalSave( fn, graphData );
          } else {
            checkError()();
          }
        } );
      } else {
        checkError()();
        return;
      }
    },
    normalSave: function( success, graphData ) {
      var $this = this;

      ShowTitleMessage.show( "正在保存..." );
      if ( editData.editType == 1 ) {
        // 编辑文章
        $this.articleSubmit( $.parseJSON( graphData )[ 0 ], success );
      } else {
        // 编辑图文
        $this.graphSubmit( graphData, success );
      }
    },
    reprintCheck: function( callback, checkError ) {

      var $this = this,
        cotnent = [],
        jsonData = editData.graphDataDetails;
      for ( i in jsonData ) {
        var article = jsonData[ i ];
        cotnent.push( {
          content: article.content || article.page_content,
          title: article.title
        } );
      }

      function titleTextSet( json ) {
        $( '.mine', this ).text( json.title );
        $( '.other', this ).text( json.otitle ).prop( 'href', '/article?p=' + json.pid );
        if ( $.isFunction( checkError ) ) {
          checkError();
        }
      }
      ShowTitleMessage.show( '正在进行文章验证' );
      $.ajax( {
        type: 'post',
        url: '/edit_text/checkReprint',
        data: {
          content: JSON.stringify( cotnent )
        },
        success: function( data ) {
          ShowTitleMessage.hide();
          data = $.parseJSON( data );
          if ( data.ret == 0 ) {
            if ( $.isFunction( callback ) ) {
              callback.call( $this, $this.saveSuccess, $this.graphData );
            }
          } else if ( data.ret === 80233 ) {
            $( '#reprint_modal' ).modal();
            titleTextSet.call( $( '#reprint_modal' ), data.data );
          } else if ( data.ret === 80234 ) {
            $( '#NO_reprint_modal' ).modal();
            titleTextSet.call( $( '#NO_reprint_modal' ), data.data );
          } else {
            ShowTitleMessage.showWarning( data.msg, showTime );
          }
        }
      } );
    }
  }

  ! function() {

    function batchModify( key, value ) {
      if ( typeof key == 'object' ) {
        for ( i in editData.graphDataDetails ) {
          $.extend( editData.graphDataDetails[ i ], key );
          delete editData.graphDataDetails[ i ][ 'templateCheck' ];
        }
      } else {
        for ( i in editData.graphDataDetails ) {
          editData.graphDataDetails[ i ][ key ] = value;
          delete editData.graphDataDetails[ i ][ 'templateCheck' ];
        }
      }

    }
    // 保存并群发
    self.on( 'click', '#save-send', function() {
      batchModify( 'isAllCheck', 1 );
      $( 'button', self ).prop( 'disabled', 'disabled' );
      returnParam.doSaveGraph( function( articleGroupID ) {
        window.onbeforeunload = undefined;
        var sendBack = bu.getUrlParam( 'edit_sign' );
        if ( sendBack ) {
          articleGroupID += '&edit_sign=1';
        }
        location.href = '/sending?article_group=' + articleGroupID;
      }, function() {
        $( 'button', self ).removeAttr( 'disabled' );
      } );
    } ).on( 'click', '#save-all', function() {
      // 保存
      var thisBtn = $( this );
      var data = editData.graphDataDetails;
      $( 'button', self ).prop( 'disabled', 'disabled' );
      // 发布的时候再check
      /*for (i in data) {
        if (!data[i].declare_original || data[i].declare_original) {
          data[i].isAllCheck = 0;
        }
      }*/
      batchModify( {
        'isAllCheck': 0,
        'need_publish': '0'
      } );

      returnParam.doSaveGraph( function() {
        $( 'button', self ).removeAttr( 'disabled' );
      }, function() {
        $( 'button', self ).removeAttr( 'disabled' );
      } );

    } ).on( 'click', '#preview-graph', function( e ) {
      // 预览
      e.stopPropagation();
      $( '.side_btn .mer_mbar', combiner.$selector ).trigger( 'click' );
    } ).on( 'click', '#save-release', function() {
      // 保存并发布
      var me = $( this );
      $( 'button', self ).prop( 'disabled', 'disabled' );
      // 设置发布
      editData.setAttrbute( {
        'need_publish': '1',
        'isAllCheck': 1
      } );

      returnParam.doSaveGraph( function() {
        location.href = '/my_resource';
      }, function() {
        $( 'button', self ).removeAttr( 'disabled' );
      } );

    } ).on( 'click', '#save-long-pictur', function() {
      // 存为长图
      var currentObj = editData.getCurrentArticle();
      if ( currentObj.content === '' ) {
        ShowTitleMessage.showWarning( '请先补充正文内容再生成长图', showTime );
      } else {
        returnParam.doSaveGraph( function( data ) {
          if ( typeof data === 'object' && data.ret !== undefined && data.ret !== 0 ) return;
          $( '#WxMsgViewForm' ).prop( 'src', "/Home/SinaImage/html_to_img/pid/" + currentObj.article_id );
          ShowTitleMessage.show( '正在获取长图', showTime );
        } );
      }
    } ).on( 'click', '#saveas_template', function() {
      // 存为模板
      batchModify( 'isAllCheck', 0 );
      var currtObj = editData.getCurrentArticle(),
        pic = $( 'img', currtObj.content ).eq( 0 ).attr( 'src' ) || '',
        title = currtObj.title || '';
      currtObj[ 'templateCheck' ] = !0;

      function saveTemplate() {
        ShowTitleMessage.show( '正在保存模板' );
        var cd = currtObj[ 'article_id' ],
          tid = currtObj[ 'tid' ] || '';
        if ( cd ) {
          $.ajax( {
            url: BIGWE_API.TEMPLATE.CREATE_SAVE_TEMPLATE,
            type: 'post',
            data: {
              pcode: cd,
              pic: pic,
              title: title + '—模板',
              tid: tid
            },
            success: function( data ) {
              data = $.parseJSON( data );
              if ( !data.ret ) {
                ShowTitleMessage.show( '模板保存成功，<a href="/template?tid=' + data.data.tid + '" target="_blank" style="color: inherit;text-decoration: underline;">点击进入编辑模板</a>', 7e3 );
                currtObj[ 'tid' ] = data.data.tid;
              } else {
                ShowTitleMessage.showWarning( data.msg || '保存失败', showTime );
              }
            }
          } );
        }
      }
      // 存为模板
      if ( editData.isContentChange ) {
        returnParam.doSaveGraph( saveTemplate );
      } else {
        saveTemplate();
      }
    } );

    // 署名转载确认
    $( '#reprint_modal .btn-success' ).click( function() {
      $( '#reprint_modal' ).modal( 'hide' );
      returnParam.normalSave( returnParam.saveSuccess, returnParam.graphData );
    } );

    $( '#reprint_modal, #NO_reprint_modal' ).on( 'hide.bs.modal', function() {
      $( 'button', self ).removeAttr( 'disabled' );
    } );
    $( '.label_classify .btn-cancel,.label_classify .close span' ).click( function() {
      batchModify( 'isAllCheck', 0 );
    } );
  }();

  return returnParam;
} );